package com.oocl.action;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.oocl.entity.Book;

public class AddToShoppingCart extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int bid = Integer.valueOf(request.getParameter("bid"));
		String bname = (String) request.getParameter("bname");
		int price = Integer.valueOf(request.getParameter("price"));
		String picture = (String) request.getParameter("picture");
		Book book = new Book(bid, bname, price, picture);
		
		HttpSession session = request.getSession();
		
		// bookList to store books.
		Map<Book, Integer> bookList = (Map<Book, Integer>) session.getAttribute("bookList");
		
		if (bookList == null) {
			bookList = new HashMap<Book, Integer>();
			bookList.put(book, 1);
		}else{
			if (bookList.get(book)!=null) {
				int amount = bookList.get(book);
				bookList.put(book, amount+1);
			}else{
				bookList.put(book, 1);
			}
		}
		
		session.removeAttribute("bookList");
		session.setAttribute("bookList", bookList);
		response.sendRedirect("shoppingCart.jsp");
	}

}
